package driver;

import environment.Environment;
import agent.AgentTable;

public class SystemDriver implements Runnable {
	
	MoveQueue moveList;
	Environment map;
	public AgentTable reference;
	
	public SystemDriver( Environment map, MoveQueue moveList, AgentTable reference ) {
		
		this.map = map;
		this.moveList = moveList;
		this.reference = reference;
	}
	
	// method to add a move object to move queue
	public void queueMove( Move latest ) {
		
		moveList.enqueue( latest );
	}
	
	// method to notify agent object if move attempt was successful
	public void moveResult( int agentID, int result ) {
		
		reference.allAgents.get( agentID ).moveSuccess = result;
	}
	
	// method that runs within the thread
	public void run() {
		
		// infinite loop while thread is active
		while( true ) {
			
			// if move queue is not empty, first move is dequeued
			if( moveList.isEmpty() == false ) {
				
				Move temp = moveList.dequeue();
				
				// if move location is not occupied, move is executed and agent object is notified
				if( map.agentArray[ temp.getYLoc() ][ temp.getXLoc() ] == -1 ) {
					
					map.executeMove( temp.getAgentID(), temp.getXLoc(), temp.getYLoc() );
					moveResult( temp.getAgentID(), 1 );
				}
				// if move location is occupied, agent is notified
				else {
					
					moveResult( temp.getAgentID(), -1 );
				}
			}
		}
	}
}
